const app = getApp();
const api = require('../../utils/api.js');

Page({
  data: {
    // 记录数据
    allRecords: [],
    filteredRecords: [],
    
    // 统计数据
    totalSessions: 0,
    totalHours: 0,
    completionRate: 0,
    
    // 筛选和排序
    currentFilter: 'all',
    sortBy: 'date',
    
    // 分页
    pageSize: 20,
    currentPage: 1,
    hasMore: true,
    loading: false,
    refreshing: false,
    
    // 详情弹窗
    showDetailModal: false,
    selectedRecord: null
  },

  onLoad() {
    this.loadRecords();
  },

  onShow() {
    // 刷新数据
    this.loadRecords();
  },

  // 加载记录数据
  async loadRecords() {
    try {
      // 检查用户是否已登录
      const token = wx.getStorageSync('token');
      if (!token) {
        // 如果未登录，显示空记录
        this.setData({
          allRecords: []
        });
        return;
      }
      
      // 如果已登录，从服务器获取记录
      const response = await api.getTreatmentRecords();
      const serverRecords = response.records || [];
      
      // 格式化服务器记录为本地记录格式
      const formattedRecords = serverRecords.map(record => ({
        id: record.id,
        date: record.created_at,
        duration: record.treatment_duration,
        actual_duration: record.actual_duration,
        params: {
          mode: record.treatment_mode,
          current: record.current_intensity,
          time: record.treatment_duration,
          frequency: record.frequency
        },
        completed: record.status === 'completed'
      }));
      
      // 按时间倒序排列
      formattedRecords.sort((a, b) => new Date(b.date) - new Date(a.date));
      
      this.setData({
        allRecords: formattedRecords
      });
      
      // 计算统计数据
      this.calculateStats(formattedRecords);
      
      // 应用筛选
      this.applyFilter();
      
    } catch (error) {
      console.error('加载治疗记录失败:', error);
      
      // 显示空记录
      this.setData({
        allRecords: []
      });
      
      // 计算统计数据
      this.calculateStats([]);
      
      // 应用筛选
      this.applyFilter();
      
      // 显示错误提示
      if (error.message && error.message.includes('401')) {
        wx.showToast({
          title: '请先登录',
          icon: 'none'
        });
      } else {
        wx.showToast({
          title: '加载记录失败',
          icon: 'none'
        });
      }
    }
  },
      

  // 计算统计数据
  async calculateStats(records) {
    // 基础统计
    const totalSessions = records.length;
    const totalMinutes = records.reduce((sum, record) => sum + record.duration, 0);
    const totalHours = Math.round(totalMinutes / 60 * 10) / 10;
    const completedSessions = records.filter(record => record.completed).length;
    const completionRate = totalSessions > 0 ? Math.round(completedSessions / totalSessions * 100) : 0;
    
    // 初始化统计数据
    let stats = {
      totalSessions,
      totalHours,
      completionRate,
      avgIntensity: 0,
      modeDistribution: [],
      dailyTreatments: []
    };
    
    // 如果用户已登录，从服务器获取更详细的统计数据
    const token = wx.getStorageSync('token');
    if (token) {
      try {
        const response = await api.getTreatmentStatistics();
        stats = {
          totalSessions: response.total_treatments,
          totalHours: Math.round(response.total_treatments * 20 / 60 * 10) / 10, // 简化计算
          completionRate: response.completion_rate,
          avgIntensity: response.avg_intensity,
          modeDistribution: response.mode_distribution,
          dailyTreatments: response.daily_treatments
        };
      } catch (error) {
        console.error('获取详细统计数据失败:', error);
      }
    }
    
    this.setData({
      totalSessions: stats.totalSessions,
      totalHours: stats.totalHours,
      completionRate: stats.completionRate,
      avgIntensity: stats.avgIntensity,
      modeDistribution: stats.modeDistribution,
      dailyTreatments: stats.dailyTreatments
    });
  },

  // 设置筛选条件
  setFilter(e) {
    const filter = e.currentTarget.dataset.filter;
    this.setData({
      currentFilter: filter,
      currentPage: 1
    });
    this.applyFilter();
  },

  // 应用筛选
  applyFilter() {
    let filtered = [...this.data.allRecords];
    const now = new Date();
    
    switch (this.data.currentFilter) {
      case 'today':
        const today = new Date(now.getFullYear(), now.getMonth(), now.getDate());
        filtered = filtered.filter(record => {
          const recordDate = new Date(record.date);
          return recordDate >= today && recordDate < new Date(today.getFullYear(), today.getMonth(), today.getDate() + 1);
        });
        break;
        
      case 'week':
        // 计算本周第一天（周日）
        const weekStart = new Date(now);
        weekStart.setDate(now.getDate() - now.getDay());
        weekStart.setHours(0, 0, 0, 0);
        
        // 计算下周第一天（下周日）
        const nextWeekStart = new Date(weekStart);
        nextWeekStart.setDate(weekStart.getDate() + 7);
        
        filtered = filtered.filter(record => {
          const recordDate = new Date(record.date);
          return recordDate >= weekStart && recordDate < nextWeekStart;
        });
        break;
        
      case 'month':
        const monthStart = new Date(now.getFullYear(), now.getMonth(), 1);
        const nextMonthStart = new Date(now.getFullYear(), now.getMonth() + 1, 1);
        filtered = filtered.filter(record => {
          const recordDate = new Date(record.date);
          return recordDate >= monthStart && recordDate < nextMonthStart;
        });
        break;
        
      case 'completed':
        filtered = filtered.filter(record => record.completed);
        break;
        
      default: // 'all'
        // 不进行筛选，显示所有记录
        break;
    }
    
    // 应用排序
    this.applySorting(filtered);
  },

  // 设置排序方式
  setSortBy(e) {
    const sortBy = e.currentTarget.dataset.sort;
    this.setData({ sortBy });
    this.applyFilter();
  },

  // 应用排序
  applySorting(records) {
    switch (this.data.sortBy) {
      case 'date':
        records.sort((a, b) => new Date(b.date) - new Date(a.date));
        break;
      case 'duration':
        records.sort((a, b) => b.duration - a.duration);
        break;
    }
    
    // 分页处理
    const pageSize = this.data.pageSize;
    const currentPage = this.data.currentPage;
    const startIndex = 0;
    const endIndex = currentPage * pageSize;
    const paginatedRecords = records.slice(startIndex, endIndex);
    
    this.setData({
      filteredRecords: paginatedRecords,
      hasMore: records.length > endIndex
    });
  },

  // 下拉刷新
  onRefresh() {
    this.setData({ refreshing: true });
    
    setTimeout(() => {
      this.loadRecords();
      this.setData({ refreshing: false });
    }, 1000);
  },

  // 加载更多
  loadMore() {
    if (this.data.loading || !this.data.hasMore) return;
    
    this.setData({ 
      loading: true,
      currentPage: this.data.currentPage + 1
    });
    
    setTimeout(() => {
      this.applyFilter();
      this.setData({ loading: false });
    }, 500);
  },

  // 查看记录详情
  viewRecordDetail(e) {
    const record = e.currentTarget.dataset.record;
    this.setData({
      selectedRecord: record,
      showDetailModal: true
    });
  },

  // 关闭详情弹窗
  closeDetailModal() {
    this.setData({
      showDetailModal: false,
      selectedRecord: null
    });
  },

  // 删除记录
  deleteRecord() {
    wx.showModal({
      title: '确认删除',
      content: '确定要删除这条治疗记录吗？',
      success: (res) => {
        if (res.confirm) {
          const recordId = this.data.selectedRecord.id;
          let records = wx.getStorageSync('treatmentRecords') || [];
          
          records = records.filter(record => record.id !== recordId);
          wx.setStorageSync('treatmentRecords', records);
          
          this.setData({
            showDetailModal: false,
            selectedRecord: null
          });
          
          // 刷新数据
          this.loadRecords();
          
          wx.showToast({
            title: '删除成功',
            icon: 'success'
          });
        }
      }
    });
  },

  // 重复治疗
  repeatTreatment() {
    const params = this.data.selectedRecord.params;
    
    // 更新全局治疗参数
    app.globalData.treatmentParams = { ...params };
    
    this.setData({
      showDetailModal: false,
      selectedRecord: null
    });
    
    // 跳转到首页
    wx.switchTab({
      url: '/pages/index/index',
      success: () => {
        wx.showToast({
          title: '参数已加载',
          icon: 'success'
        });
      }
    });
  },

  // 格式化日期
  formatDate(dateString) {
    const date = new Date(dateString);
    const now = new Date();
    const today = new Date(now.getFullYear(), now.getMonth(), now.getDate());
    const yesterday = new Date(today);
    yesterday.setDate(today.getDate() - 1);
    
    if (date >= today) {
      return '今天';
    } else if (date >= yesterday) {
      return '昨天';
    } else {
      const month = (date.getMonth() + 1).toString().padStart(2, '0');
      const day = date.getDate().toString().padStart(2, '0');
      return `${month}-${day}`;
    }
  },

  // 格式化时间
  formatTime(dateString) {
    const date = new Date(dateString);
    const hours = date.getHours().toString().padStart(2, '0');
    const minutes = date.getMinutes().toString().padStart(2, '0');
    return `${hours}:${minutes}`;
  },

  // 格式化完整日期
  formatFullDate(dateString) {
    const date = new Date(dateString);
    const year = date.getFullYear();
    const month = (date.getMonth() + 1).toString().padStart(2, '0');
    const day = date.getDate().toString().padStart(2, '0');
    const hours = date.getHours().toString().padStart(2, '0');
    const minutes = date.getMinutes().toString().padStart(2, '0');
    
    return `${year}-${month}-${day} ${hours}:${minutes}`;
  },

  // 格式化时长
  formatDuration(minutes) {
    // 使用toFixed替代方案，确保保留一位小数
    const rounded = Math.round(minutes * 10) / 10;
    // 确保小数点后有一位数字
    const str = rounded.toString();
    return str.indexOf('.') > -1 ? 
      (str.split('.')[1].length == 1 ? str : str + '0') : 
      str + '.0';
  },

  // 获取完成度评分
  getCompletionScore(actualDuration, plannedDuration) {
    const percentage = actualDuration / plannedDuration;
    
    if (percentage >= 0.9) return 'A+';
    if (percentage >= 0.8) return 'A';
    if (percentage >= 0.7) return 'B+';
    if (percentage >= 0.6) return 'B';
    if (percentage >= 0.5) return 'C+';
    if (percentage >= 0.4) return 'C';
    return 'D';
  },

  // 获取评分样式类
  getScoreClass(actualDuration, plannedDuration) {
    const percentage = actualDuration / plannedDuration;
    
    if (percentage >= 0.8) return 'excellent';
    if (percentage >= 0.6) return 'good';
    if (percentage >= 0.4) return 'fair';
    return 'poor';
  },

  // 获取效果标题
  getEffectTitle(actualDuration, plannedDuration) {
    const percentage = actualDuration / plannedDuration;
    
    if (percentage >= 0.9) return '治疗效果优秀';
    if (percentage >= 0.8) return '治疗效果良好';
    if (percentage >= 0.6) return '治疗效果一般';
    if (percentage >= 0.4) return '治疗效果较差';
    return '治疗未完成';
  },

  // 获取效果描述
  getEffectDescription(actualDuration, plannedDuration) {
    const percentage = actualDuration / plannedDuration;
    
    if (percentage >= 0.9) {
      return '完成度很高，治疗效果预期良好，请继续保持规律治疗。';
    } else if (percentage >= 0.8) {
      return '基本完成治疗计划，效果较好，建议按时完成后续治疗。';
    } else if (percentage >= 0.6) {
      return '治疗时间偏短，可能影响效果，建议下次完整完成治疗。';
    } else if (percentage >= 0.4) {
      return '治疗时间不足，效果有限，请尽量完成完整的治疗时间。';
    } else {
      return '治疗中断，建议重新开始完整的治疗流程。';
    }
  }
});